package ru.gr.alphaversion;
	import org.json.JSONArray;
	import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;


		public class Cats extends ActivityGroup implements OnClickListener { 
			public static final int QRS_ID = 225225;
			static String[] iname,inames, iprices, iquas, iids, idescs, idesc, iprice, iqua, iid, ifots, ifot;
			public static String value = null, ovalue = null;
			public int con;
			public static String good;
			public static String id_item, name_item, price_item, desc, qua_item, fot_item;
			private static String isgoods;
			public static boolean check;
			public String act;
			

			@Override
				  /** Called when the activity is first created. */
				  public void onCreate(Bundle savedInstanceState) {
				SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
				System.out.println(Integer.parseInt(sp.getString("list","0")));
				switch (Integer.parseInt(sp.getString("list","0"))) {
				case 2:
					setTheme(android.R.style.Theme_Light_NoTitleBar_Fullscreen);
					System.out.println("выбрано 2");
					break;
				case 1: 
					setTheme(android.R.style.Theme_Black_NoTitleBar_Fullscreen);
					System.out.println("выбрано 1");
					break;
				default:
					setTheme(android.R.style.Theme_Black_NoTitleBar_Fullscreen);
					System.out.println("выбрано 0");
				}
				    super.onCreate(savedInstanceState);
				    setContentView(R.layout.cats);
				    Main.checkk=3;
				    
				    View cbackButton = findViewById(R.id.cat_back);
				    cbackButton.setOnClickListener(this);
				  //  check = false;
				    if (getIntent().getExtras()!= null)
				    {
				    value = getIntent().getExtras().getString("Pid");
				    act = getIntent().getExtras().getString("act");
				    ovalue = getIntent().getExtras().getString("PPid");
				    
				    if(act!=null) {
				    	desc=(getIntent().getExtras().getString("desc"));
				    	qua_item=getIntent().getExtras().getString("qua_item");
				        id_item = getIntent().getExtras().getString("ItemId");
						price_item = getIntent().getExtras().getString("price_item");
						fot_item = getIntent().getExtras().getString("fot_item");
				    }
				    
				    }
				    if (act!=null)
		    		{
		    	
		    	/*desc=(getIntent().getExtras().getString("desc"));
		    	qua_item=getIntent().getExtras().getString("qua_item");
		        id_item = getIntent().getExtras().getString("ItemId");
				price_item = getIntent().getExtras().getString("price_item");
				Intent findItem_1 = new Intent(Cats.this,ItemDescription.class);
				findItem_1.putExtra("ItemId", id_item);
				findItem_1.putExtra("price_item", price_item);
				findItem_1.putExtra("desc", desc);
				findItem_1.putExtra("qua_item", qua_item);
				findItem_1.putExtra("act", "3");*/
				//startActivity(findItem_1);
				
				if (Cats.check) {
					
					Intent findItem_1 = new Intent(Cats.this,ItemDescription.class);
					findItem_1.putExtra("ItemId", id_item);
					findItem_1.putExtra("price_item", price_item);
					findItem_1.putExtra("desc", desc);
					findItem_1.putExtra("qua_item", qua_item);
					findItem_1.putExtra("cat_id", Cats.value);
					findItem_1.putExtra("fot_item", fot_item);
					findItem_1.putExtra("act", "3");
					//Cats parentActivity = (Cats)getParent();
					//parentActivity.
					//startActivity(findItem_1);
					Main.checkk=3;
					replaceContentView("find_ok", findItem_1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
					Cats.check = false;
				} else {
	    			Cats parentActivity_ok = (Cats)getParent();
	    			desc=(getIntent().getExtras().getString("desc"));
			    	qua_item=getIntent().getExtras().getString("qua_item");
			        id_item = getIntent().getExtras().getString("ItemId");
					price_item = getIntent().getExtras().getString("price_item");
					fot_item = getIntent().getExtras().getString("fot_item");
					Intent findItem_1 = new Intent(Cats.this,ItemDescription.class);
					findItem_1.putExtra("ItemId", id_item);
					findItem_1.putExtra("price_item", price_item);
					findItem_1.putExtra("desc", desc);
					findItem_1.putExtra("qua_item", qua_item);
					findItem_1.putExtra("cat_id", Cats.value);
					findItem_1.putExtra("fot_item", fot_item);
					findItem_1.putExtra("act", "3");
					parentActivity_ok.replaceContentView("find_ok", findItem_1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
					Main.checkk=3;
				}
				
		    		} else {
				    if(value==null)
				    {
				    	value = "0";
				    }
				    String [] inames = new String[500];
				    String [] iprices = new String[500];
				    String [] iquas = new String[500];
				    String [] iids = new String[500];
				    String [] ifots = new String[500];
				    boolean onl = isOnline(); 
				    if (onl){
				    GetJSON json = new GetJSON();
				    
					try {
						String gg = json.postData( value, "", "QCatalog", "", this);
						JSONObject jsonObject = new JSONObject(gg);
						if(gg!="") {
							if(jsonObject.getString("error").equals("1")) {
								
								Toast toast = Toast.makeText(this, R.string.no_cat_name, Toast.LENGTH_LONG);
				    			toast.setGravity(Gravity.CENTER, 0, 0);
				    			toast.show();
								//Cats.this.finish();
							} else {
								//JSONArray jsonArray = new JSONArray(jsonObject.getString("items"));
								//JSONObject jsonObject_1 = jsonArray.getJSONObject(0);
								
								good = jsonObject.getString("isgood");
								//Toast.makeText(this, good, Toast.LENGTH_LONG).show();
								JSONArray jsonObject_1 = jsonObject.getJSONArray("cats");
						//		System.out.println(jsonObject_1.length());
								con = jsonObject_1.length();
								
								//
								for (int i = 0; i<(jsonObject_1.length()); i++) {
								//	//System.out.println(jsonObject_1.getJSONObject(i)
								//			.getString("NAME").toString());
								//	System.out.println(jsonObject_1.getJSONObject(i).getString(
									//		"ID").toString());
								//	
								
								desc = jsonObject_1.getJSONObject(i).getString("NAME");
								id_item = jsonObject_1.getJSONObject(i).getString("ID");
								
								iids[i] = id_item;
								inames[i] = desc;
								if(good.equals("1")){
								price_item= jsonObject_1.getJSONObject(i).getString("PRICE");
								qua_item= jsonObject_1.getJSONObject(i).getString("QUANTITY");
								fot_item = jsonObject_1.getJSONObject(i).getString("FOTO");
								ifots[i] = fot_item;
								iprices[i] = price_item;
								iquas[i] = qua_item;
								}				
							}
							}
						} else {
							//Toast.makeText(this, "��� ���������� � ��������", Toast.LENGTH_LONG).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}}
				    else {
				    	if(!Cats.check)
				    	{
				    	new AlertDialog.Builder(this)
			            .setTitle("Ошибка")
			            .setMessage("Нет ответа от сервера")
			            .setPositiveButton(android.R.string.yes, null).create().show();}
				    	else {
				    		Cats parentActivity = (Cats)getParent();
				    		new AlertDialog.Builder(parentActivity)
				            .setTitle("Ошибка")
				            .setMessage("Нет ответа от сервера")
				            .setPositiveButton(android.R.string.yes, null).create().show();}
				    		
				    	}
				    	
				    
					//String [] iname = new String[con];
					
					//String [] Cats.iid = new String[con];
					Cats.isgoods = good;
					Cats.iname = ResizeArrary(inames,con);
					Cats.iid = ResizeArrary(iids,con);
					Cats.iprice = ResizeArrary(iprices,con);
					Cats.iqua = ResizeArrary(iquas,con);
					Cats.ifot = ResizeArrary(ifots,con);
					inames = null;
					iids = null;
					iprices = null;
					iquas = null;
					ifots = null;					
					  // ������� ������
				    ListView slist = (ListView) findViewById(R.id.cats);
				    slist.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

				    // ������� �������
				    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				        android.R.layout.simple_list_item_1, iname);

				    // ����������� ������� ������
				    slist.setAdapter(adapter);
				//    Toast.makeText(this, good+"#", Toast.LENGTH_LONG).show();
				    slist.setOnItemClickListener(new OnItemClickListener() {
				        public void onItemClick(AdapterView<?> parent, View view,
				            int position, long id) {
				        	Intent intent;
				        		//
				        	
				//			Log.d("", "itemClick: position = " + good + ", id = "
				 //             + Cats.isgoods);
				        	
							if (!good.equals("1"))
							{
				        	    //intent = new Intent(Cats.this,Cats.class);
								//intent.putExtra("Pid", Cats.iid[(int)id]);		  
								//startActivity(intent);
								//Cats parentActivity = (Cats)getParent();
								//parentActivity.
								//startActivity(intent);
								if (!Cats.check) {
									Intent itemfind_ok = new Intent(Cats.this, Cats.class);
					    			//Cats parentActivity_ok = (Cats)getParent();
					    			itemfind_ok.putExtra("Pid", Cats.iid[(int)id]);
					    			itemfind_ok.putExtra("PPid", Cats.value);
					    			//parentActivity_ok.
					    			Cats.check = true;
					    			replaceContentView("find_ok", itemfind_ok);
					    			
					    			
								} else {
									Intent itemfind_ok = new Intent(Cats.this, Cats.class);
								//	boolean log = (Cats)getParent() != null;
									if (false){
					    			Cats parentActivity_ok = (Cats)getParent();
					    			itemfind_ok.putExtra("Pid", Cats.iid[(int)id]);
					    			itemfind_ok.putExtra("PPid", Cats.value);
					    			parentActivity_ok.replaceContentView("find_ok", itemfind_ok.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
									} else {
										//Intent itemfind_ok = new Intent(Cats.this, Cats.class);
						    			//Cats parentActivity_ok = (Cats)getParent();
						    			itemfind_ok.putExtra("Pid", Cats.iid[(int)id]);
						    			itemfind_ok.putExtra("PPid", Cats.value);
						    			//parentActivity_ok.
						    			Cats.check = true;
						    			replaceContentView("find_ok", itemfind_ok);
									}
								}
							}
							else {
								
								if (!check) {
									//Intent findItem_1 = new Intent(Cats.this, Cats.class);
					    		//	Cats parentActivity_ok = (Cats)getParent();
									Intent findItem_1 = new Intent(Cats.this,ItemDescription.class);
									//Intent findItem_1 = new Intent(Cats.this,Cats.class);
									findItem_1.putExtra("ItemId", Cats.iid[(int)id]);
									findItem_1.putExtra("Pid", Cats.value);
									findItem_1.putExtra("price_item", Cats.iprice[(int)id]);
									findItem_1.putExtra("cat_id", Cats.value);
									findItem_1.putExtra("desc", Cats.iname[(int)id]);
									findItem_1.putExtra("qua_item", Cats.iqua[(int)id]);
									findItem_1.putExtra("fot_item", Cats.ifot[(int)id]);
									findItem_1.putExtra("act", "3");
									//Cats parentActivity = (Cats)getParent();
									//parentActivity.
									//startActivity(findItem_1);
									replaceContentView("find_ok", findItem_1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
									//Cats.this.finish();
									check = false;
								} else {
									Intent findItem_1 = new Intent(Cats.this, ItemDescription.class);
					    		//	Cats parentActivity_ok = (Cats)getParent();
									
									//Intent findItem_1 = new Intent(Cats.this,Cats.class);
									findItem_1.putExtra("ItemId", Cats.iid[(int)id]);
									findItem_1.putExtra("price_item", Cats.iprice[(int)id]);
									findItem_1.putExtra("cat_id", Cats.value);
									findItem_1.putExtra("desc", Cats.iname[(int)id]);
									findItem_1.putExtra("qua_item", Cats.iqua[(int)id]);
									findItem_1.putExtra("fot_item", Cats.ifot[(int)id]);
									findItem_1.putExtra("act", "3");
									//Cats parentActivity = (Cats)getParent();
									//parentActivity.
									//startActivity(findItem_1);
									//parentActivity_ok.
									replaceContentView("find_ok", findItem_1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
								//Cats.this.finish();
								}
							}
				        }

						
				      });
				    
				    slist.setOnItemSelectedListener(new OnItemSelectedListener() {
				        public void onItemSelected(AdapterView<?> parent, View view,
				            int position, long id) {
				          Log.d("", "itemSelect: position = " + position + ", id = "
				              + id);
				        }
				        public void onNothingSelected(AdapterView<?> parent) {
				            Log.d("", "itemSelect: nothing");
				          }
				    });
		    		}
				  }

			
			public void onClick(View v) {
				switch (v.getId()) {
		    	case R.id.cat_back: 
		    		if (value!="0")
		    		{
		    		Intent itemfind_ok = new Intent(Cats.this, Cats.class);
	    			//Cats parentActivity_ok = (Cats)getParent();
	    			itemfind_ok.putExtra("Pid", "0");
	    			//parentActivity_ok.
	    			replaceContentView("find_ok", itemfind_ok);
		    		}
				}
			}
			
			
			public void replaceContentView(String id, Intent newIntent) {
			    //	View view = getLocalActivityManager().startActivity(id, newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView(); 
			    //	this.setContentView(view);
			//	@SuppressWarnings("unused")
			//	ViewGroup view1 = (ViewGroup)getWindow().getDecorView();
				
			//	((ViewManager) view1).removeView(view1);
				
			    		View view = ((ActivityGroup)((Activity)this)).getLocalActivityManager()
			    	            .startActivity(id,
			    	                    newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
			    	            .getDecorView();
			    //		((ViewManager) view).removeView(view);
			        	((ActivityGroup)((Activity)this)).setContentView(view);
			    	
			    }
			public String[] ResizeArrary(String [] arr, Integer c )   {
			    String[] array2 = new String[c];
			    for (int i = 0; i < c; i++) {
			        array2[i] = arr[i];
			    }
			    return array2;    
			}  
			public boolean isOnline() {
				    ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
				    NetworkInfo nInfo = cm.getActiveNetworkInfo();
				    if (nInfo != null && nInfo.isConnected()) {
				        Log.v("status", "ONLINE");
				        return true;
				    }
				    else {
				        Log.v("status", "OFFLINE");
				        return false;
				    }
				}
			
			
			protected void onPause()
			{
				super.onPause();
			//	System.out.println("pause");
		//		Cats.this.finish();
			}
			protected void onStop()
			{
				super.onStop();
		//		System.out.println("stop");
			}
			protected void onDestroy()
			{
				super.onDestroy();
			//	System.out.println("destroy");
			}
			
			
			@Override
		    public void onBackPressed() {
				
				
				GetJSON json = new GetJSON();
				try {
					String gg = json.postData( Cats.value, "", "QGetParent", "", this);
					JSONObject jsonObject = new JSONObject(gg);
					if(gg!="") {
						if(jsonObject.getString("error").equals("1")) {
							
							Toast toast = Toast.makeText(this, R.string.no_cat_name, Toast.LENGTH_LONG);
			    			toast.setGravity(Gravity.CENTER, 0, 0);
			    			toast.show();
							//Cats.this.finish();
						} else {
						
							
							String Pid = jsonObject.getString("cat");
							Intent itemfind_ok = new Intent(Cats.this, Cats.class);
			    			//Cats parentActivity_ok = (Cats)getParent();
			    			itemfind_ok.putExtra("Pid", Pid);
			    			//parentActivity_ok.
			    			replaceContentView("find_ok", itemfind_ok.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
								
						}
						
					} else {
						//Toast.makeText(this, "��� ���������� � ��������", Toast.LENGTH_LONG).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
		    }
	}

